package spectra.ee.web.common.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.Writer;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import spectra.base.log.LP;
import spectra.base.log.Logger;
import spectra.base.util.StringUtil;

public class SaveContentsBaseServlet extends HttpServlet
{
    /**
     * 자동 생성한  Serializable 클래스의 UID 
     */
    private static final long serialVersionUID = 6718902715001763987L;
    
    /** Logger 객체. */
    private static Logger logger = Logger.getLoggerInstance(SaveContentsBaseServlet.class.getName());

    /**
    * <pre>
    * Parameter 는 fileInfo 하나이며 암호화된 값을 받는다.
    * 암호화된 값은 배열형태로 리턴된다.(FILEINFO 배열)
    * FILEINFO[0] : 다운로드할 실제 디렉토리로 부터 파일 이름까지 Full Path.
    * FILEINFO[1] : 다운로드시 보여줄 파일명.
    * </pre>
    *
    * @param req HttpServletRequest 객체.
    * @param res HttpServletResponse 객체.
    *
    * @throws IOException Signals that an I/O exception has occurred.
    * @throws ServletException the servlet exception
    */
    public void doPost(HttpServletRequest req, HttpServletResponse res)
            throws IOException, ServletException
    {
        req.setCharacterEncoding("UTF-8");
        String contents = req.getParameter("contents");
        contents = StringUtil.defaultIfBlank(contents, "There is no contents.");
        String fileName = req.getParameter("fileName");
        fileName = StringUtil.defaultIfBlank(fileName, "NoTitle");
        
        
        String fileType = req.getParameter("fileType");
        fileType = StringUtil.defaultIfBlank(fileType, "html");
        
        res.setContentType("application/octet-stream; charset=utf-8");

        String strHeader = "";
        String userAgent = req.getHeader("User-Agent");

        if (userAgent.indexOf("MSIE 5.5") > -1)  // MS IE 5.5 이하
        {
            fileName = URLEncoder.encode(fileName.replaceAll(" ", ""), "UTF-8");
            strHeader = "filename=\"" + fileName+"."+fileType + "\";";
        }
        else if (userAgent.indexOf("MSIE") > -1)  // MS IE (보통은 6.x 이상 가정)
        {
            fileName = URLEncoder.encode(fileName.replaceAll(" ", ""), "UTF-8");
            strHeader = "attachment; filename=\"" + fileName+"."+fileType + "\";";
        }
        else  // 모질라나 오페라
        {
            fileName = new String(fileName.getBytes("UTF-8"), "latin1");
            strHeader = "attachment; filename=\"" + fileName+"."+fileType + "\";";
        }

        res.setHeader("Content-Disposition", strHeader);

        char[] ch = new char[1024];

        StringReader reader = new StringReader(contents);
        Writer writer = res.getWriter();
        int read = 0;
        try
        {
            while ((read = reader.read(ch)) != -1)
            {
                writer.write(ch,0,read);
            }
            reader.close();
            writer.flush();
            writer.close();
        }
        catch (Exception e)
        {
            errorPrintln(res, null);
            logger.error(LP.EXCEPTION, e);
        }
        finally
        {
            if (reader != null)
            {
                reader.close();
            }
        }
    }
    
    /**
     * 주어진 에러페이지로 이동한다.<br/>
     * 에러페이지가 null 이거나 비어 있으면 에러페이지를 만들어 보낸다.
     *
     * @param res HttpServletResponse 객체.
     * @param strErrorPage 에러페이지 URL.
     *
     * @throws IOException Signals that an I/O exception has occurred.
     * @throws ServletException the servlet exception
     */
    protected void errorPrintln(HttpServletResponse res, String strErrorPage)
            throws IOException, ServletException
    {
        if (strErrorPage == null || strErrorPage.length() == 0)
        {
            PrintWriter out = res.getWriter();
            res.setContentType("text/html");
            out.println("<html><head><title></title></head><body>");
            out.println("There is no contents. !!");
            out.println("</body></html>");
            out.close();
        }
        else
        {
            res.sendRedirect(strErrorPage);
        }
    }    
}
